package in.muton.wicket.extensions.upload;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.DynamicWebResource;
import org.apache.wicket.protocol.http.WebRequest;

public class UploadProcessStatusResource extends DynamicWebResource {

	private static final long serialVersionUID = 3627825885799673234L;
	private static Log log = LogFactory.getLog(UploadProcessStatusResource.class);	
	
	@Override
	protected ResourceState getResourceState() {
		return new UploadProcessResourceState();
	}
	
	private class UploadProcessResourceState extends DynamicWebResource.ResourceState{

		/** uploaded count|total count|transfer rate|time remaining|processing stage */
		private String status;
		
		public UploadProcessResourceState(){
			HttpServletRequest req = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest();
			UploadProcessInfo info = (UploadProcessInfo)UploadProcessWebRequest.getUploadInfo(req);
			if(info==null || info.getTotalBytes() < 1){
				status = "0|0|0|0|0";
			}else{
				status = "" + info.getPercentageComplete() + "|" + info.getBytesUploadedString() +
				"|" + info.getTotalBytesString() + "|" + info.getTransferRateString() +
				"|" + info.getRemainingTimeString() + "|" + UploadProcessInfo.PROCESSING_NOT_STARTED;
			}
			
			log.debug("Status: "+status);
			status = "<html>|"+status+"|</html>";
			
		}
		@Override
		public String getContentType() {
			return "text/plain";
		}

		@Override
		public byte[] getData() {
			return status.getBytes();
		}
		
		@Override
		public int getLength() {
			return status.length();
		}
	}

}
